package com.hnkywl.sts.action.jhgl;

import com.hnkywl.sts.action.flow.assign.RegectTaskSingleBackWayCmd;
import com.hnkywl.sts.entity.jhgl.*;
import com.hnkywl.sts.entity.organ.Nbgs;
import com.hnkywl.sts.entity.sys.Gncz;
import com.hnkywl.sts.entity.sys.Yg;
import com.hnkywl.sts.service.flow.FlowService;
import com.hnkywl.sts.service.jhgl.JkdService;
import com.hnkywl.sts.service.jhgl.ZjjhService;
import com.hnkywl.sts.service.organ.NbgsService;
import com.hnkywl.sts.service.sys.GnczService;
import com.hnkywl.sts.service.sys.YgService;
import net.ruixin.web.struts2.SimpleActionSupport;
import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.jbpm.api.*;
import org.jbpm.api.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * User: ZHUCHG
 * Date: 13-4-9
 * Time: 下午8:29
 * To change this template use File | Settings | File Templates.
 */
@Namespace("/jhgl/zjjhgl")
public class ZjjhglAction extends SimpleActionSupport {

    private Long id;
    private Long xyId;
    private String xyType;
    private Long wzjhId;
    private String wzjhType;
    //类型
    private String type;
    //计划年份
    private String jhnf;
    //计划月份
    private String jhyf;
    //上报公司ID
    private Long sbgsId;
    //申报机构ID
    private Long sbbmId;
    //审批状态
    private String zt;
    //分页组件 起始位置
    private int page;
    //分页组件 页面大小
    private int rows;

    private Date date;

    private Yg yg;
    private Long ygGsId;
    private Long gsId;
    private String ygGs;
    private String ygName;
    private String ygGsbm;
    //总公司
    private Nbgs zgs;
    private Long cghtId;

    private Tpzjjh tpzjjh;
    private Zgzjjh zgzjjh;
    private List<Zgzjjhmx> zgzjjhmxList;
    private List<Tpzjjhmx> tpzjjhmxList;

    private ZjjhService zjjhService;
    private NbgsService nbgsService;
    private Jkd jkd;
    private YgService ygService;
    private JkdService jkdService;
    private Long zgwzjhId;


    private String result;

    private String taskId;

    private String content;

    private String processInstanceId;

    private String executionId;

    private FlowService flowService;

    private ProcessEngine processEngine;

    private TaskService taskService;

    private ExecutionService executionService;

    private HistoryService historyService;

    private String jhbh;


    //功能操作
    private List<Gncz> gnczList;
    private GnczService gnczService;

    private String jkdIds;
    //完成金额
    private double wcje;
    //完成率
    private double wcl;
    //是否审批页面
    private String jhsp;

    private Long gysId;

    @Action("zjjhgl")
    public String zjjhgl() {
        date = initStartDate();
        gnczList = gnczService.findGnczByJsAndUrl(request.getServletPath());
        return SUCCESS;
    }

    private Date initStartDate() {
        Calendar cal = Calendar.getInstance();
        int year = cal.get(cal.YEAR);
        int month = cal.get(cal.MONTH);
        cal.set(Calendar.YEAR, year);
        cal.set(Calendar.MONTH, month);
        cal.set(Calendar.DATE, 1);
        return cal.getTime();
    }

    @Action("zjjhgl_content")
    public String zjjhglContent() {
        yg = YgService.getCurrentYg();
        gsId = YgService.getCurrentYgGsId();
        ygGsId = YgService.getCurrentYgZgGsId();
        if ("Zgzjjh".equalsIgnoreCase(type) && id != null) {
            zgzjjh = zjjhService.findZgzzjh(id);
        }
        if ("Tpzjjh".equalsIgnoreCase(type) && id != null) {
            tpzjjh = zjjhService.findTpzjjh(id);
        } else {

            ygGs = YgService.getCurrentYgZgGs();
            ygName = YgService.getCurrentYgName();
            ygGsbm = YgService.getCurrentYgZgGsCode();
            List<Nbgs> roots = nbgsService.findAllRootNbgs();
            if (!CollectionUtils.isEmpty(roots))
                zgs = roots.get(0);
        }
        date = initStartDate();
        return SUCCESS;
    }

    @Action("add_tpjkd")
    public String addTpjkd() {
        Yg g = ygService.findYgDetail(YgService.getCurrentYg().getId());
        Tpzjjh tpzjjh1 = this.zjjhService.findTpzjjh(id);
        jkd = new Jkd();
        jkd.setType("tp");
        jkd.setGys(tpzjjh1.getGys());
        jkd.setJkgs(tpzjjh1.getSbgs());
        if (g.getZgjg().className().equals("Nbbm")) {
            jkd.setJkjg(g.getZgjg());
        } else {
            jkd.setJkjg(null);
        }
        jkd.setSqr(g);
        jkd.setTpzjjh(tpzjjh1);
        return SUCCESS;
    }

    @Action("add_zgjkd")
    public String addZgjkd() {
        Zgzjjh zgzjjh = this.zjjhService.findZgzzjh(id);

        jkd = new Jkd();
        jkd.setType("zg");
        jkd.setJkgs(zgzjjh.getCggs());
        jkd.setSbgs(zgzjjh.getSbgs());
        jkd.setSbbm(zgzjjh.getSbbm());
        jkd.setSbr(zgzjjh.getSbr());
        jkd.setSqr(YgService.getCurrentYg());
        jkd.setZgzjjh(zgzjjh);

        return SUCCESS;
    }

    @Action("add_jkd")
    public void addJkd() {
        try {
            this.jkdService.saveJkd(jkd);
            renderText("{\"statusCode\":\"200\", \"message\":\"借款单生成成功!\"}");
        } catch (Exception e) {
            e.printStackTrace();
            renderText("{\"statusCode\":\"300\", \"message\":\"" + e.getMessage() + "\"}");
        }
    }

    @Action("zjjhList")
    public void zjjhList() {
        renderJson(zjjhService.findList(type, jhnf, jhyf, gysId, sbgsId, sbbmId, zt,jhbh, page, rows));
    }

    @Action("initTpzjjhmx")
    public void initTpzjjhmx() {
        renderJson(zjjhService.findPmByTpwzjh(id));
    }

    @Action("zjjhgl_detail")
    public String zjjhglDetail() {
        wcje = zjjhService.findFkje(id, type);
        if ("Zgzjjh".equalsIgnoreCase(type)) {
            if (id != null) {
                zgzjjh = zjjhService.findZgzzjh(id);
                if (zgzjjh.getZgwzjh() != null) {
                    wzjhId = zgzjjh.getZgwzjh().getId();
                    wzjhType = zgzjjh.getZgwzjh().getClass().getSuperclass().getSimpleName();
                    if (zgzjjh.getZgwzjh().getXy() != null) {
                        xyId = zgzjjh.getZgwzjh().getXy().getId();
                        xyType = zgzjjh.getZgwzjh().getXy().getClass().getSimpleName();
                    }
                }
            }
            BigDecimal bg = new BigDecimal(wcje / zgzjjh.getSbje() * 100); //保留2位小数
            wcl = bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        }
        if ("Tpzjjh".equalsIgnoreCase(type)) {
            if (id != null) {
                tpzjjh = zjjhService.findTpzjjh(id);
                if (tpzjjh.getTpwzjh() != null) {
                    wzjhId = tpzjjh.getTpwzjh().getId();
                    wzjhType = tpzjjh.getTpwzjh().getClass().getSuperclass().getSimpleName();
                    if (tpzjjh.getTpwzjh().getXy() != null) {
                        xyId = tpzjjh.getTpwzjh().getXy().getId();
                        xyType = tpzjjh.getTpwzjh().getXy().getClass().getSimpleName();
                    }
                }
            }
            BigDecimal bg = new BigDecimal(wcje / tpzjjh.getSbje()); //保留2位小数
            wcl = bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        }
        return SUCCESS;
    }

    @Action("zjjhmxList")
    public void zjjhmxList() {
        if ("Zgzjjh".equalsIgnoreCase(type)) {
            renderText(zjjhService.findZgzjjhmxByZgzjjh(id));
            return;
        } else if ("Tpzjjh".equalsIgnoreCase(type)) {
            renderText(zjjhService.findTpzjjhmxByTpzjjh(id));
            return;
        }
    }

    @Action("jkdList")
    public void jkdList() {
        renderText(jkdService.findJkdByZjjh(id, type));
    }

    @Action("save_zjjh")
    public void save() {
        try {
            if ("Zgzjjh".equalsIgnoreCase(type)) {
                zjjhService.saveZgzjjh(zgzjjh, zgzjjhmxList);
                renderText("{\"statusCode\":\"200\", \"message\":\"保存自购资金计划成功!\"}");
                return;
            } else if ("Tpzjjh".equalsIgnoreCase(type)) {
                zjjhService.saveTpzjjh(tpzjjh, tpzjjhmxList);
                renderText("{\"statusCode\":\"200\", \"message\":\"保存统配资金计划成功!\"}");
                return;
            }
            renderText("{\"statusCode\":\"300\", \"message\":\"资金计划类型参数错误!\"}");
        } catch (Exception e) {
            e.printStackTrace();
            renderText("{\"statusCode\":\"300\", \"message\":\"" + e.getMessage() + "\"}");
        }
    }


    @Action("edit_zjjh")
    public void edit() {
        try {
            if ("Zgzjjh".equalsIgnoreCase(type)) {
                zgzjjh.setLastUpdated(new Date());
                zjjhService.editZgzjjh(zgzjjh, zgzjjhmxList);
                renderText("{\"statusCode\":\"200\", \"message\":\"修改自购物资计划成功!\"}");
                return;
            } else if ("Tpzjjh".equalsIgnoreCase(type)) {
                tpzjjh.setLastUpdated(new Date());
                zjjhService.editTpzjjh(tpzjjh, tpzjjhmxList);
                renderText("{\"statusCode\":\"200\", \"message\":\"修改统配物资计划成功\"}");
                return;
            }
            renderText("{\"statusCode\":\"300\", \"message\":\"物资计划类型参数错误!\"}");
        } catch (Exception e) {
            e.printStackTrace();
            renderText("{\"statusCode\":\"300\", \"message\":\"" + e.getMessage() + "\"}");
        }
    }

    @Action("delete")
    public void delete() {
        try {
            if ("Zgzjjh".equalsIgnoreCase(type)) {
                zjjhService.deleteZgzjjh(id);
                renderText("{\"statusCode\":\"200\", \"message\":\"删除自购资金计划成功!\"}");
                return;
            } else if ("Tpzjjh".equalsIgnoreCase(type)) {
                zjjhService.deleteTpzjjh(id);
                renderText("{\"statusCode\":\"200\", \"message\":\"删除统配资金计划成功\"}");
                return;
            }
            renderText("{\"statusCode\":\"300\", \"message\":\"资金计划类型参数错误!\"}");
        } catch (Exception e) {
            e.printStackTrace();
            renderText("{\"statusCode\":\"300\", \"message\":\"" + e.getMessage() + "\"}");
        }
    }

    @Action("commit_zjjh")
    public void commitWzjh() {
        try {
            if ("zgzjjh".equalsIgnoreCase(type)) {
                zgzjjh = zjjhService.findZgzzjh(id);
                String processName = "自购资金计划流程";
                if (this.flowService.checkFlowStart(processName)) {
                    String contain = StringUtils.EMPTY;
//                    if (zgzjjh.getZgwzjh().getZbcg() == null || !zgzjjh.getZgwzjh().getZbcg())
//                        contain = "协议";
                    String processInstanceId = flowService.regTask(zgzjjh.getProcessInstanceId(), processName, contain);
                    zgzjjh.setProcessInstanceId(processInstanceId);
                    zgzjjh.setZt("ytj");
                } else
                    zgzjjh.setZt("ysp");
                zjjhService.saveZgzjjh(zgzjjh);
                renderJson("{\"statusCode\":\"200\", \"message\":\"提交自购资金计划成功!\"}");
                return;
            }
            if ("tpzjjh".equalsIgnoreCase(type)) {
                tpzjjh = zjjhService.findTpzjjh(id);
                String processName = "统配资金计划流程";
                if (this.flowService.checkFlowStart(processName)) {
                    String processInstanceId = this.flowService.regTask(tpzjjh.getProcessInstanceId(), processName, null);
                    tpzjjh.setProcessInstanceId(processInstanceId);
                    tpzjjh.setZt("ytj");
                } else
                    tpzjjh.setZt("ysp");
                zjjhService.saveTpzjjh(tpzjjh);
                renderJson("{\"statusCode\":\"200\", \"message\":\"提交统配资金计划成功!\"}");
                return;
            }
            renderJson("{\"statusCode\":\"300\", \"message\":\"资金计划类型参数错误!\"}");
        } catch (Exception e) {
            e.printStackTrace();
            renderJson("{\"statusCode\":\"300\", \"message\":\"" + e.getMessage() + "\"}");
        }
    }


    @Action("zjjhByProcessInstance")
    public void zjjhByProcessInstance() {
        Execution execution = this.executionService.findExecutionById(executionId);
        if ("Zgzjjh".equalsIgnoreCase(type)) {
            Zgzjjh zgzjjh;
            String processInstanceId = StringUtils.EMPTY;
            if (execution != null){
                zgzjjh = this.zjjhService.findZgzjjhDetailByProcessInstance(execution.getProcessInstance().getId());
                processInstanceId = execution.getProcessInstance().getId();
            }else{
                zgzjjh = this.zjjhService.findZgzjjhDetailByProcessInstance(executionId);
                processInstanceId = executionId;
            }
            String zgzjjhJson = "{'id':'" + zgzjjh.getId() + "','type':'Zgzjjh','businessNo':'" + zgzjjh.getJhbh() + "','processInstanceId':'" + processInstanceId + "'}";
            this.renderText(zgzjjhJson);
        } else if ("Tpzjjh".equalsIgnoreCase(type)) {
            Tpzjjh tpzjjh;
            String processInstanceId = StringUtils.EMPTY;
            if (execution != null){
                tpzjjh = this.zjjhService.findTpzjjhDetailByProcessInstance(execution.getProcessInstance().getId());
                processInstanceId = execution.getProcessInstance().getId();
            }else{
                tpzjjh = this.zjjhService.findTpzjjhDetailByProcessInstance(executionId);
                processInstanceId = executionId;
            }
            String xyJson = "{'id':'" + tpzjjh.getId() + "','type':'Tpzjjh','businessNo':'" + tpzjjh.getJhbh() + "','processInstanceId':'" + processInstanceId + "'}";
            this.renderText(xyJson);
        }
    }


    @Action(value = "examineTask")
    public void examineTask() {
        if (this.result.equals("审核")) {
            Map<String, Object> var = new HashMap<String, Object>();
            var.put("owner", YgService.getCurrentYg().getId());
            var.put("opera", YgService.getCurrentYgGs() + "--" + YgService.getCurrentYgName());
            var.put("result", "审核通过");
            var.put("content", content);
            var.put("time", new Date());
            Task currentTask = this.taskService.getTask(taskId);
            String executionId = currentTask.getExecutionId();
            executionService.createVariables(executionId, var, true);


            Execution execution = this.executionService.findExecutionById(executionId);
            if ("Zgzjjh".equalsIgnoreCase(type)) {
                Zgzjjh zgzjjh = zjjhService.findZgzjjhDetailByProcessInstance(execution.getProcessInstance().getId());
                var.put("status", result);
//                if (zgzjjh.getZgwzjh() != null && zgzjjh.getZgwzjh().getXy() != null)
//                    var.put("contain", "协议");
//                else
                    var.put("contain", StringUtils.EMPTY);
                this.taskService.completeTask(taskId, var);

                if (zgzjjh.getZt().equals("ybc")) {
                    zgzjjh.setZt("ytj");
                    zjjhService.saveZgzjjh(zgzjjh);
                }
            } else {
                Tpzjjh tpzjjh = zjjhService.findTpzjjhDetailByProcessInstance(execution.getProcessInstance().getId());
                var.put("status", result);
                this.taskService.completeTask(taskId, var);

                if (tpzjjh.getZt().equals("ybc")) {
                    tpzjjh.setZt("ytj");
                    zjjhService.saveTpzjjh(tpzjjh);
                }
            }
        } else {
            String result = processEngine.execute(new RegectTaskSingleBackWayCmd(taskId, content));
            if (result.equals("change")) {
                //修改状态  ytj--->ybc
                String executionId = this.historyService.createHistoryTaskQuery().taskId(taskId).uniqueResult().getExecutionId();
                Execution execution = this.executionService.findExecutionById(executionId);
                if ("Zgzjjh".equalsIgnoreCase(type)) {
                    Zgzjjh zgzjjh = zjjhService.findZgzjjhDetailByProcessInstance(execution.getProcessInstance().getId());
                    zgzjjh.setZt("ybc");
                    zjjhService.saveZgzjjh(zgzjjh);
                } else {
                    Tpzjjh tpzjjh = zjjhService.findTpzjjhDetailByProcessInstance(execution.getProcessInstance().getId());
                    tpzjjh.setZt("ybc");
                    zjjhService.saveTpzjjh(tpzjjh);
                }
            }
        }
        this.renderText("{\"statusCode\":\"200\", \"message\":\"审核流程成功\"}");
    }
    //================setter  getter===================

    public Tpzjjh getTpzjjh() {
        return tpzjjh;
    }

    public void setTpzjjh(Tpzjjh tpzjjh) {
        this.tpzjjh = tpzjjh;
    }

    public Zgzjjh getZgzjjh() {
        return zgzjjh;
    }

    public void setZgzjjh(Zgzjjh zgzjjh) {
        this.zgzjjh = zgzjjh;
    }

    public List<Zgzjjhmx> getZgzjjhmxList() {
        return zgzjjhmxList;
    }

    public void setZgzjjhmxList(List<Zgzjjhmx> zgzjjhmxList) {
        this.zgzjjhmxList = zgzjjhmxList;
    }

    public List<Tpzjjhmx> getTpzjjhmxList() {
        return tpzjjhmxList;
    }

    public void setTpzjjhmxList(List<Tpzjjhmx> tpzjjhmxList) {
        this.tpzjjhmxList = tpzjjhmxList;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }


    //================getter===================
    public Date getDate() {
        return date;
    }

    public String getYgGs() {
        return ygGs;
    }

    public Long getGsId() {
        return gsId;
    }

    public Long getYgGsId() {
        return ygGsId;
    }

    public String getYgName() {
        return ygName;
    }

    public String getYgGsbm() {
        return ygGsbm;
    }

    public Nbgs getZgs() {
        return zgs;
    }

    public List<Gncz> getGnczList() {
        return gnczList;
    }

    //================setter===================
    public void setJhnf(String jhnf) {
        this.jhnf = jhnf;
    }

    public void setJhyf(String jhyf) {
        this.jhyf = jhyf;
    }

    public void setSbgsId(Long sbgsId) {
        this.sbgsId = sbgsId;
    }

    public void setSbbmId(Long sbbmId) {
        this.sbbmId = sbbmId;
    }

    public void setGsId(Long gsId) {
        this.gsId = gsId;
    }

    public void setZt(String zt) {
        this.zt = zt;
    }

    public void setPage(int page) {
        this.page = page;
    }

    public void setRows(int rows) {
        this.rows = rows;
    }

    public Jkd getJkd() {
        return jkd;
    }

    public void setJkd(Jkd jkd) {
        this.jkd = jkd;
    }

    public Long getCghtId() {
        return cghtId;
    }

    public void setCghtId(Long cghtId) {
        this.cghtId = cghtId;
    }

    public Long getZgwzjhId() {
        return zgwzjhId;
    }

    public void setZgwzjhId(Long zgwzjhId) {
        this.zgwzjhId = zgwzjhId;
    }

    public String getResult() {
        return result;
    }

    public void setResult(String result) {
        this.result = result;
    }

    public String getTaskId() {
        return taskId;
    }

    public void setTaskId(String taskId) {
        this.taskId = taskId;
    }

    public String getProcessInstanceId() {
        return processInstanceId;
    }

    public void setProcessInstanceId(String processInstanceId) {
        this.processInstanceId = processInstanceId;
    }

    public String getExecutionId() {
        return executionId;
    }

    public void setExecutionId(String executionId) {
        this.executionId = executionId;
    }

    public Yg getYg() {
        return yg;
    }

    public void setYg(Yg yg) {
        this.yg = yg;
    }

    public String getJkdIds() {
        return jkdIds;
    }

    public void setJkdIds(String jkdIds) {
        this.jkdIds = jkdIds;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public double getWcje() {
        return wcje;
    }

    public void setWcje(double wcje) {
        this.wcje = wcje;
    }

    public double getWcl() {
        return wcl;
    }

    public void setWcl(double wcl) {
        this.wcl = wcl;
    }

    public String getJhsp() {
        return jhsp;
    }

    public void setJhsp(String jhsp) {
        this.jhsp = jhsp;
    }

    public Long getXyId() {
        return xyId;
    }

    public void setXyId(Long xyId) {
        this.xyId = xyId;
    }

    public String getXyType() {
        return xyType;
    }

    public void setXyType(String xyType) {
        this.xyType = xyType;
    }

    public Long getWzjhId() {
        return wzjhId;
    }

    public void setWzjhId(Long wzjhId) {
        this.wzjhId = wzjhId;
    }

    public String getWzjhType() {
        return wzjhType;
    }

    public void setWzjhType(String wzjhType) {
        this.wzjhType = wzjhType;
    }

    public Long getGysId() {
        return gysId;
    }

    public void setGysId(Long gysId) {
        this.gysId = gysId;
    }

    public String getJhbh() {
        return jhbh;
    }

    public void setJhbh(String jhbh) {
        this.jhbh = jhbh;
    }

    @Autowired
    public void setZjjhService(ZjjhService zjjhService) {
        this.zjjhService = zjjhService;
    }

    @Autowired
    public void setNbgsService(NbgsService nbgsService) {
        this.nbgsService = nbgsService;
    }

    @Autowired
    public void setYgService(YgService ygService) {
        this.ygService = ygService;
    }

    @Autowired
    public void setJkdService(JkdService jkdService) {
        this.jkdService = jkdService;
    }

    @Autowired
    public void setFlowService(FlowService flowService) {
        this.flowService = flowService;
    }

    @Autowired
    public void setExecutionService(@Qualifier("executionService") ExecutionService executionService) {
        this.executionService = executionService;
    }

    @Autowired
    public void setTaskService(@Qualifier("taskService") TaskService taskService) {
        this.taskService = taskService;
    }

    @Autowired
    public void setProcessEngine(@Qualifier("processEngine") ProcessEngine processEngine) {
        this.processEngine = processEngine;
    }

    @Autowired
    public void setHistoryService(@Qualifier("historyService") HistoryService historyService) {
        this.historyService = historyService;
    }

    @Autowired
    public void setGnczService(GnczService gnczService) {
        this.gnczService = gnczService;
    }


}
